package com.bds.btcdc.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration
public class DruidDataSourceConfig {
    @Autowired
    Environment environment;

    @Bean
    public DataSource druidDataSource() throws Exception {
        Properties properties = new Properties();
        properties.put("url", environment.getProperty("spring.datasource.url"));
        properties.put("username", environment.getProperty("spring.datasource.username"));
        properties.put("password", environment.getProperty("spring.datasource.password"));
        properties.put("driver", environment.getProperty("spring.datasource.driver-class-name"));
        properties.put("type", environment.getProperty("spring.datasource.type"));
        return DruidDataSourceFactory.createDataSource(properties);
    }

    /**
     * 注册一个StatViewServlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        return servletRegistrationBean;
    }

    /**
     *注册一个：filterRegistrationBean
     * @param druidServletRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean(ServletRegistrationBean druidServletRegistrationBean) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter(), druidServletRegistrationBean);
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;

    }
}
